<template>
  <el-dialog
    v-model="dialogFormVisible"
    :title="title"
    width="500px"
    @close="close"
  >
    <el-form ref="formRef" label-width="80px" :model="form" :rules="rules">
      <el-form-item v-if="!currentType" label="所属平台" prop="ownPlatform">
        <el-select v-model="form.ownPlatform" value-key="ownPlatform">
          <el-option
            v-for="item in dictData"
            :key="item.ownPlatform"
            :label="item.label"
            :value="item.ownPlatform"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="!currentType" label="平台账号" prop="platformAccount">
        <el-input v-model.trim="form.platformAccount" />
      </el-form-item>
      <el-form-item label="运营人员" prop="operateId">
        <el-select v-model="form.operateId" value-key="id">
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="客服人员" prop="customerId">
        <el-select v-model="form.customerId" value-key="id" multiple="true">
          <el-option
            v-for="item in list"
            :key="item.id"
            :label="item.nickname"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item v-if="!currentType" label="登陆账号" prop="accountNumber">
        <el-input v-model.trim="form.accountNumber" />
      </el-form-item>
      <el-form-item v-if="!currentType" label="登陆密码" prop="accountPassword">
        <el-input v-model.trim="form.accountPassword" />
      </el-form-item>
      <el-form-item v-if="!currentType && title === '添加'" label="确认密码">
        <el-input v-model.trim="verificationPw" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" @click="save">确 定</el-button>
    </template>
  </el-dialog>
</template>

<script>
  // import { doAdd, doEdit } from '@/api/userManagement'
  import {
    editAccount,
    addAccount,
    editDistributionAccount,
  } from '@/api/accountManagement'
  import { fetchDictSelectList } from '@/api/dictionaryManagement'
  import { getList } from '@/api/userManagement'

  export default defineComponent({
    name: 'UserManagementEdit',
    props: {
      roles: {
        type: Array,
        default: () => {
          return []
        },
      },
    },
    emits: ['fetch-data'],
    setup(props, { emit }) {
      const $baseMessage = inject('$baseMessage')

      const state = reactive({
        formRef: null,
        form: {
          roleIds: [],
        },
        rules: {
          ownPlatform: [
            { required: true, trigger: 'blur', message: '请选择所属平台' },
          ],
          platformAccount: [
            { required: true, trigger: 'blur', message: '请输入平台账号' },
          ],
          // operateId: [
          //   { required: true, trigger: 'blur', message: '请选择运营人员' },
          // ],
          // customerId: [
          //   { required: true, trigger: 'blur', message: '请选择客服人员' },
          // ],
          accountNumber: [
            { required: true, trigger: 'blur', message: '请输入登录账号' },
          ],
          accountPassword: [
            { required: true, trigger: 'blur', message: '请输入密码' },
          ],
        },
        title: '',
        dialogFormVisible: false,
        dictData: [],
        listLoading: false,
        list: [],
        verificationPw: '',
        currentType: '',
      })

      const fetchDictLists = async () => {
        const typeCode = {
          typeCode: 'accountType',
        }
        const { data: data } = await fetchDictSelectList(typeCode)
        data.forEach((item) => {
          item.value = Number(item.value)
          item.ownPlatform = item.value
        })
        state.dictData = data
      }

      const showEdit = (row, allot, ids) => {
        if (!row) {
          if (!allot) {
            state.title = '添加'
          } else {
            state.title = '分配'
            state.currentType = allot
            state.form.id = ids
          }
        } else {
          state.title = '编辑'
          state.form = JSON.parse(JSON.stringify(row))
        }
        state.dialogFormVisible = true
      }
      const close = () => {
        state['formRef'].resetFields()
        state.form = {
          roles: [],
        }
        state.dialogFormVisible = false
      }
      const save = () => {
        state['formRef'].validate(async (valid) => {
          if (valid) {
            if (state.currentType !== 'allot') {
              if (state.title === '添加') {
                if (state.verificationPw !== state.form.accountPassword) {
                  $baseMessage('两次密码输入不一致', 'warning')
                  return
                }
              }
            }
            try {
              state.form.customerId = state.form.customerId.toString()
              const { msg } =
                state.title === '添加'
                  ? await addAccount(state.form)
                  : state.title === '编辑'
                  ? await editAccount(state.form)
                  : await editDistributionAccount(state.form)
              $baseMessage(msg, 'success', 'vab-hey-message-success')
              emit('fetch-data')
              close()
              state.form = {}
              state.verificationPw = ''
            } catch (err) {
              console.error(err)
            }
          }
        })
      }
      const fetchDataUser = async () => {
        try {
          state.listLoading = true
          const queryForm = {
            pageNum: 1,
            pageSize: 999,
          }
          const {
            data: { list },
          } = await getList(queryForm)
          state.list = list
          state.listLoading = false
        } catch (e) {
          console.log(e)
        }
      }
      onMounted(() => {
        fetchDictLists()
        fetchDataUser()
      })
      return {
        ...toRefs(state),
        showEdit,
        close,
        save,
      }
    },
  })
</script>
